<?php

namespace control;
/*
*科目辅助明细账类
*/

class subjectAssetDetailsClass extends adIndexClass
{
    private const page = 'subjectAssetDetails';
    private const title = '科目辅助明细账';
    public const typeOption = ['期初金额', '本期合计', '本年累计'];
    public static bool $isFormat = false;//是否格式化数字

    /**
     * 模糊查询科目
     */
    public function getSubject(): bool|string
    {
        $component = new componentClass();
        $val = $this->post('keyword');//关键词
        $showParent = (bool)$this->post('showParent');
        $json['data'] = [];
        $where = " and coid='" . self::$coid . "' and assistAccount = '是' and (id in (select distinct b.subjectId from voucher as a join voucher_detail as b on a.id = b.orderId where 1=1 " . voucherClass::joinWhere() . ") or id in (select id from subject_assist where orderId = id and initMoney !=0))";
        if ($val) {
            $where .= " and (name like '%$val%' or code like '%$val%' or concat(code,' ',name) like '%$val%')";
        }

        $subjectIds = [];
        $all = find(array('table' => 'subject', 'where' => "1=1 $where order by code asc"));
        foreach ($all['array'] as $array) {
            $res = $component->loopSubject($array['id'], $where, $showParent);
            $subjectIds = array_merge($subjectIds, $res);
        }
        $subjectIds = array_unique($subjectIds);
        foreach ($subjectIds as $id) {
            $subject = query('subject', "id = '$id'");
            $json['data'][] = array('title' => $subject['code'] . ' ' . $subject['name'], 'direction' => $subject['direction'], 'id' => $subject['id']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $subject = query("subject", "coid='" . self::$coid . "' and assistAccount = '是' and (id in (select distinct b.subjectId from voucher as a join voucher_detail as b on a.id = b.orderId where 1=1 " . voucherClass::joinWhere() . ") or id in (select id from subject_assist where orderId = id and initMoney !=0)) order by code");
        if (empty($subject['id'])) {
            $subject = query('subject', "coid = '" . self::$coid . "' order by code");
        }
        $maxDate = accountDetailsClass::getMaxDate();
        $minDate = accountDetailsClass::getMinDate();
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "会计期间" => text(array("name" => "createTime", 'value' => static::rGet(self::$stid .self::$coid. 'SearchMonth') ?: date('Y-m',strtotime($maxDate)) . ' ~ ' . date('Y-m',strtotime($maxDate)),  'laydate' => ['type' => 'month','range'=>'~','min'=>"'{$minDate}'",'max'=>"'{$maxDate}'"])),
                    "科目"   => componentClass::selectText(array('name' => 'subjectId', 'title' => $subject['code']?($subject['code'] . ' ' . $subject['name']):'', 'cla' => self::page, 'fun' => 'getSubject', 'value' => $subject['id'])),
                    '客户' => clientProfileClass::kehuSelect(array('title' => '', 'name' => 'khid', 'fun' => 'getClientNameAndCode')),
                ],
                [
                    '供应商'  => supplierClass::supplierSelect(['name' => 'supplierId', 'fun' => 'getSupplier', 'title' => '']),
                    "员工" => selectMultiple(array('name' => 'staffId', 'table' => 'staff', 'where' => "1=1 order by orderNo asc", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200')),
                    '部门' => selectMultiple(array('name' => 'departmentId', 'field' => "concat(orderNo,name) as name,id", 'table' => 'department', 'where' => "1=1 order by orderNo asc", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200')),
                ],
                [
                    "存货" => componentClass::selectText(['name' => 'materialId', 'title' => '', 'cla' => 'voucherEdit', 'fun' => 'getMaterial']),
                    "现金流" => selectMultiple(array('name' => 'cashId', 'field' => "concat(code,name) as name,id", 'table' => 'cash', 'where' => "coid='" . self::$coid . "' order by code asc", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200')),
                    "项目" => selectMultiple(array('name' => 'projectId', 'field' => "concat(orderNo,name) as name,id", 'table' => 'project', 'where' => "coid='" . self::$coid . "' order by orderNo asc", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200')),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }


    /*客户列表-查询结果*/
    public function homeSearch()
    {
        static::rSet(self::$stid .self::$coid. 'SearchMonth', $this->post('createTime'));;
        $json['html'] = $this->onlyMoneySearch();
        return json_encode($json, 320);
    }


    private function js()
    {
        return <<<eof
<style>
.bold{font-weight: bold}
</style>
eof;
    }

    /**
     * 金额式
     */
    public function onlyMoneySearch(): string
    {
        $subjectSearch = query('subject', "id = '" . $this->post('subjectId') . "'");
        $subjectWhere = " and subjectId = '" . $this->post('subjectId') . "'";
        $subjectAssitWhere = " and orderId = '" . $this->post('subjectId') . "'";
        $like = array();
        //全等查询数组
        $equal = array(
            "a.coid" => self::$coid,
            "a.isTemplate" => '否',
        );
        $assetField = array(
            "khid" => $this->post('khid'),
            "supplierId" => $this->post('supplierId'),
            "staffId" => $this->post('staffId'),
            "departmentId" => $this->post('departmentId'),
            "materialId" => $this->post('materialId'),
            "cashId" => $this->post('cashId'),
            "projectId" => $this->post('projectId'),
        );

            $and = self::timeComparison($this->post('createTime'), 'month', field: "a.recordDate");
        $arr        = $this->post('createTime') ? explode(' ~ ', $this->post('createTime')) : [date('Y-m', strtotime(accountDetailsClass::getMinDate())), date('Y-m', strtotime(accountDetailsClass::getMaxDate()))];
        $startMonth = trim($arr[0]);
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $assitWhere = search(array("=" => $assetField));
        $page = $this->page(array("table" => "subject", "where" => "coid = '" . self::$coid . "' and (id in (select distinct b.subjectId from voucher as a join voucher_detail as b on a.id = b.orderId where 1=1 " . $assitWhere . $subjectWhere . voucherClass::joinWhere() . ") or id in (select  id from subject_assist where orderId = id and initMoney !=0 $assitWhere $subjectAssitWhere))", "order" => "code asc"));

        $url = root . "control/adIndex.html?cla=voucherEdit&fun=home";
        static::rSet(self::$stid . self::page . 'assitWhere', $assitWhere);
        static::rSet(self::$stid . self::page . 'where', $where);
        static::rSet(self::$stid . self::page . 'startMonth', $startMonth);
        static::rSet(self::$stid . self::page . 'sql', $page['fullSql']);
        static::rSet(self::$stid . self::page . 'subjectId', $subjectSearch['id']);
        static::rSet(self::$stid . self::page . 'assetField', json_encode($assetField,320));
        self::$isFormat = true;
        $tr = '';
        foreach ($page['array'] as $array) {
            $all = find(array('table' => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "b.*,a.voucherNo,a.recordDate,a.voucherWordId", "where" => "b.subjectId = '$array[id]' " . $where .$assitWhere. voucherClass::joinWhere() . " order by a.recordDate asc,a.voucherNo asc,b.list"));
            if (is_array($all['array']) && count($all['array']) == 0) {
                $result = $this->initMoney($assetField['khid'], $assetField['supplierId'], $assetField['staffId'], $assetField['departmentId'], $assetField['materialId'], $assetField['cashId'], $assetField['projectId'], $array, $startMonth);
                $initDate = $startMonth . '-01';
                $tr .= <<<eof
                    <tr>
                        <td>$initDate</td>
                        <td></td>
                        <td>{$array['code']}&nbsp;{$array['name']}</td>
                        <td>期初余额</td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td>{$result['jieMoney']}</td>
                        <td>{$result['daiMoney']}</td>
                        <td>{$result['direction']}</td>
                        <td>{$result['balance']}</td>
                     </tr>
eof;
            }

            foreach ($all['array'] as $index => $item) {
                $voucherWord = query('voucher_word', "id = '$item[voucherWordId]'");
                $kehu = query('kehu', "khid = '$item[khid]'");
                $supplier = query('supplier', "id = '$item[supplierId]'");
                $staff = query('staff', "stid = '$item[staffId]'");
                $department = query('department', "id = '$item[departmentId]'");
                $material = query('material', "id = '$item[materialId]'");
                $cash = query('cash', "id = '$item[cashId]'");
                $project = query('project', "id = '$item[projectId]'");
                //期初
                if ($index == 0 || (isset($all['array'][$index - 1]['subjectId']) && $item['subjectId'] != $all['array'][$index - 1]['subjectId'])) {
                    $result = $this->initMoney(
                        $assetField['khid'],
                        $assetField['supplierId'],
                        $assetField['staffId'],
                        $assetField['departmentId'],
                        $assetField['materialId'],
                        $assetField['cashId'],
                        $assetField['projectId'],
                        $array,
                        date('Y-m', strtotime($item['recordDate']))
                    );
                    $initDate = date('Y-m', strtotime($item['recordDate'])) . '-01';
                    $tr .= <<<eof
                    <tr>
                        <td>$initDate</td>
                        <td></td>
                        <td>{$array['code']}&nbsp;{$array['name']}</td>
                        <td>期初余额</td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td>{$result['jieMoney']}</td>
                        <td>{$result['daiMoney']}</td>
                        <td>{$result['direction']}</td>
                        <td>{$result['balance']}</td>
                     </tr>
eof;
                }

                //中间的内容
                $item['money'] = voucherClass::zeroToEmpty(number_format(self::centToYuan($item['money']), 2));
                $pinzheng = $voucherWord['id'] ? componentClass::urlTitle($voucherWord['word'] . '-' . $item['voucherNo'], $url . "&id={$item['orderId']}", '录凭证') : '';
                if ($item['direction'] == '借') {
                    $jie = $item['money'];
                    $dai = '';
                } else {
                    $jie = '';
                    $dai = $item['money'];
                }
                $result = $this->balance(
                    $item['recordDate'],
                    $item['subjectId'],
                    $item['voucherNo'],
                    $assetField['khid'],
                    $assetField['supplierId'],
                    $assetField['staffId'],
                    $assetField['departmentId'],
                    $assetField['materialId'],
                    $assetField['cashId'],
                    $assetField['projectId']
                );
                $tr .= <<<eof
                     <tr>
                        <td>{$item['recordDate']}</td>
                        <td>$pinzheng</td>
                        <td>{$array['code']}&nbsp;{$array['name']}</td>
                        <td>{$item['summary']}</td>
                        <td>{$kehu['orderNo']}</td>
                        <td>{$kehu['companyName']}</td>
                        <td>{$supplier['code']}</td>
                        <td>{$supplier['name']}</td>
                        <td>{$staff['orderNo']}</td>
                        <td>{$staff['name']}</td>
                        <td>{$department['orderNo']}</td>
                        <td>{$department['name']}</td>
                         <td>{$material['code']}</td>
                        <td>{$material['name']}</td>
                        <td>{$cash['code']}</td>
                        <td>{$cash['name']}</td>
                        <td>{$project['orderNo']}</td>
                        <td>{$project['name']}</td>
                        <td>$jie</td>
                        <td>$dai</td>
                        <td>{$result['direction']}</td>
                        <td>{$result['balance']}</td>
                     </tr>
eof;
                //本期累计和本年累计
                if ((isset($all['array'][$index + 1]['subjectId']) && ($item['subjectId'] != $all['array'][$index + 1]['subjectId'] || date('Y-m', strtotime($all['array'][$index + 1]['recordDate'])) != date('Y-m', strtotime($item['recordDate'])))) ||
                    !isset($all['array'][$index + 1]['subjectId'])
                ) {

                    $interval = '';
                    if (isset($all['array'][$index + 1]['subjectId']) && $item['subjectId'] != $all['array'][$index + 1]['subjectId'] || !isset($all['array'][$index + 1]['subjectId'])) {
                        $interval = "<tr><td colspan='23' style='background-color: #f2f2f2'></td></tr>";
                    }
                    $day = sprintf("%02d", date('t', strtotime($item['recordDate'])));
                    $endMonthDate = date('Y-m-' . $day, strtotime($item['recordDate']));
                    $result = $this->monthBalance($assetField['khid'], $assetField['supplierId'], $assetField['staffId'], $assetField['departmentId'], $assetField['materialId'], $assetField['cashId'], $assetField['projectId'], date('Y-m', strtotime($item['recordDate'])), $item['subjectId']);
                    $balance = $this->balance($item['recordDate'], $item['subjectId'], '累计', $assetField['khid'], $assetField['supplierId'], $assetField['staffId'], $assetField['departmentId'], $assetField['materialId'], $assetField['cashId'], $assetField['projectId']);
                    $totalBalance = $this->monthBalance($assetField['khid'], $assetField['supplierId'], $assetField['staffId'], $assetField['departmentId'], $assetField['materialId'], $assetField['cashId'], $assetField['projectId'], date('Y-m', strtotime($item['recordDate'])), $array['id'], 'year');
                    $tr .= <<<eof
                     <tr class="bold">
                        <td>$endMonthDate</td>
                        <td></td>
                        <td>{$array['code']}&nbsp;{$array['name']}</td>
                        <td>本月合计</td>
                         <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td>{$result['jieMoney']}</td>
                        <td>{$result['daiMoney']}</td>
                        <td>{$balance['direction']}</td>
                        <td>{$balance['balance']}</td>
                     </tr>
                    <tr class="bold">
                        <td>$endMonthDate</td>
                        <td></td>
                        <td>{$array['code']}&nbsp;{$array['name']}</td>
                        <td>本年累计</td>
                         <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td>{$totalBalance['jieMoney']}</td>
                        <td>{$totalBalance['daiMoney']}</td>
                        <td>{$balance['direction']}</td>
                        <td>{$balance['balance']}</td>
                     </tr>
                    $interval
eof;
                }
            }

        }
        $subjectName = $subjectSearch['id'] ? $subjectSearch['code'] . $subjectSearch['name'] : '所有';
        $sortStr = '<span class="table-sort"><i class="table-sort-asc"></i><i class="table-sort-desc"></i></span><span class="drag">&nbsp;</span>';

        // 月份选择器
        $monthSelector = componentClass::monthSelector(implode('~',$arr));
        $html = <<<eof
<div class="finance-subject-head">科目：$subjectName {$monthSelector['button']}</div>
<table class="tableMany">
    <thead>
        <tr>
            <td sort-key="日期">日期$sortStr</td>
            <td>凭证字</td>
            <td>科目</td>
            <td>摘要</td>
            <td sort-key="客户编码">客户编码</td>
            <td>客户名称</td>
            <td sort-key="供应商编码">供应商编码</td>
            <td>供应商名称</td>
            <td sort-key="员工编码">员工编码</td>
            <td>员工名称</td>
            <td sort-key="部门编码">部门编码</td>
            <td>部门名称</td>
            <td sort-key="存货编码">存货编码</td>
            <td>存货名称</td>
            <td sort-key="现金流编码">现金流编码</td>
            <td>现金流名称</td>
            <td sort-key="项目编码">项目编码</td>
            <td>项目名称</td>
            <td>借方</td>
            <td>贷方</td>
            <td>方向</td>
            <td>余额</td>
        </tr>
    </thead>
    <tbody>
       $tr
    </tbody>
</table>
eof;
        //返回
        return $page['hint'] .
            "<div class='acct-main-container'>
                <form name='listForm'>" .
                    $html .
                "</form>" .
                $monthSelector['html'].
            "</div>" .
            $this->js() .
            $page['button'] .
            clear;
    }

    /**
     * 期初余额
     * @param $khid
     * @param $supplierId
     * @param $staffId
     * @param $departmentId
     * @param $materialId
     * @param $cashId
     * @param $projectId
     * @param $subject
     * @param $startMonth
     * @return array
     */
    public function initMoney($khid, $supplierId, $staffId, $departmentId, $materialId, $cashId, $projectId, $subject, $startMonth): array
    {
        $assetField = array(
            "khid" => $khid,
            "supplierId" => $supplierId,
            "staffId" => $staffId,
            "departmentId" => $departmentId,
            "materialId" => $materialId,
            "cashId" => $cashId,
            "projectId" => $projectId,
        );
        $where = search(array("=" => $assetField));
        //期初金额
        $initMoney = find(array(
            'table' => "subject_assist as a join subject as b on a.orderId = b.id",
            'single' => "a.orderId = '$subject[id]'" . $where,
            'field' => "ifnull(sum(a.initMoney),0) as money"
        ))['money'];

        $initNum = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'" . $where, 'sum' => "initNum"));
        $jieNum = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'" . $where, 'sum' => "jieNum"));
        $daiNum = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'" . $where, 'sum' => "daiNum"));

        $jieInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借' and date_format(a.recordDate,'%Y-%m') < '$startMonth'" . $where . voucherClass::joinWhere()));
        $daiInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷' and date_format(a.recordDate,'%Y-%m') < '$startMonth'" . $where . voucherClass::joinWhere()));
        $jieMoney = self::centToYuan($jieInit['money'] + $subject['borrowMoney']);
        $daiMoney = self::centToYuan($daiInit['money'] + $subject['loanMoney']);
        $jieInit['money'] = self::centToYuan($jieInit['money']);
        $daiInit['money'] = self::centToYuan($daiInit['money']);
        if ($subject['direction'] == '借') {
            $jieInit['money'] += $initMoney;
            $balanceNum = $jieInit['num'] + $initNum - $daiInit['num'];
        } else {
            $daiInit['money'] += $initMoney;
            $balanceNum = $daiInit['num'] + $initNum - $jieInit['num'];
        }
        if ($jieInit['money'] == $daiInit['money']) {
            $direction = '平';
            $jieMoney = 0;
            $daiMoney = 0;
            $balance = 0;
        } elseif ($jieInit['money'] > $daiInit['money']) {
            $direction = '借';
            $balance = abs($jieInit['money'] - $daiInit['money']);
        } else {
            $direction = '贷';
            $balance = abs($jieInit['money'] - $daiInit['money']);
        }
        $jieNum += $jieInit['num'];
        $daiNum += $daiInit['num'];
        $result = [
            'jieNum' => voucherEditClass::formatZero($jieNum),
            'jiePrice' => accountDetailsClass::division($jieInit['money'], $jieNum),
            'daiNum' => voucherEditClass::formatZero($daiNum),
            'daiPrice' => accountDetailsClass::division($daiInit['money'], $daiNum),
            'balanceNum' => voucherEditClass::formatZero($balanceNum),
            'balancePrice' => abs(accountDetailsClass::division($jieInit['money'] - $daiInit['money'], $balanceNum)),
            'direction' => $direction,
            'jieMoney' => round($jieMoney, 2),
            'daiMoney' => round($daiMoney, 2),
            'balance' => round($balance, 2)
        ];
        if (self::$isFormat) {
            $result = accountDetailsClass::formatArrayNumber($result);
        }
        return $result;
    }


    /**
     * 本期合计
     */
    public function monthBalance($khid, $supplierId, $staffId, $departmentId, $materialId, $cashId, $projectId, $month, $subjectId, $type = 'month'): array
    {
        $assetField = array(
            "khid" => $khid,
            "supplierId" => $supplierId,
            "staffId" => $staffId,
            "departmentId" => $departmentId,
            "materialId" => $materialId,
            "cashId" => $cashId,
            "projectId" => $projectId,
        );
        $where = search(array("=" => $assetField));
        $assistWhere = '';
        $voucherWhere = '';
        if ($subjectId) {
            $assistWhere .= " and a.orderId = '$subjectId'";
            $voucherWhere .= " and subjectId = '$subjectId'";
        }

        if ($type == 'year') {
            //期初金额
            $jieInit = find(array('table' => "subject_assist as a join subject as b on a.orderId = b.id", 'single' => "b.direction = '借'" . $where . $assistWhere, 'field' => "ifnull(sum(a.initMoney),0) as money,ifnull(sum(a.initNum),0) as num"));
            $daiInit = find(array('table' => "subject_assist as a join subject as b on a.orderId = b.id", 'single' => "b.direction = '贷'" . $where . $assistWhere, 'field' => "ifnull(sum(a.initMoney),0) as money,ifnull(sum(a.initNum),0) as num"));
            $jieMoney = $jieInit['money'];
            $daiMoney = $daiInit['money'];
            $jieNum = $jieInit['num'];
            $daiNum = $daiInit['num'];
            $year = date('Y', strtotime($month . '-01'));
            $where .= " and date_format(a.recordDate,'%Y') = '$year' and date_format(a.recordDate,'%Y-%m') <= '$month'";
        } else {
            $jieMoney = 0;
            $daiMoney = 0;
            $jieNum = $daiNum = 0;
            $where .= " and date_format(a.recordDate,'%Y-%m') = '$month'";
        }
        $jieVoucher = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' $voucherWhere and b.direction = '借'" . $where . voucherClass::joinWhere()));
        $daiVoucher = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' $voucherWhere and b.direction = '贷'" . $where . voucherClass::joinWhere()));
        $jieVoucher['money'] = self::centToYuan($jieVoucher['money']) + $jieMoney;
        $daiVoucher['money'] = self::centToYuan($daiVoucher['money']) + $daiMoney;
        $jieVoucher['num'] = $jieVoucher['num'] + $jieNum;
        $daiVoucher['num'] = $daiVoucher['num'] + $daiNum;


        if ($jieVoucher['money'] == $daiVoucher['money'] && ($jieVoucher['money'] == 0)) {
            $jieMoney = 0;
            $daiMoney = 0;
            $balance = 0;
        } elseif ($jieVoucher['money'] > $daiVoucher['money']) {
            $jieMoney = $balance = $jieVoucher['money'] - $daiVoucher['money'];
            $daiMoney = 0;
        } else {
            $jieMoney = 0;
            $daiMoney = $balance = $daiVoucher['money'] - $jieVoucher['money'];
        }

        if ($jieVoucher['num'] > $daiVoucher['num']) {
            $jieNum = $jieVoucher['num'] - $daiVoucher['num'];
            $daiNum = 0;
        } else {
            $daiNum = $daiVoucher['num'] - $jieVoucher['num'];
            $jieNum = 0;
        }

        $result = [
            'jiePrice' => accountDetailsClass::division($balance, $jieNum),
            'daiPrice' => accountDetailsClass::division($balance, $daiNum),
            'jieNum' => voucherEditClass::formatZero($jieNum),
            'daiNum' => voucherEditClass::formatZero($daiNum),
            'jieMoney' => round($jieMoney, 2),
            'daiMoney' => round($daiMoney, 2)
        ];
        if (self::$isFormat) {
            $result = accountDetailsClass::formatArrayNumber($result);
        }
        return $result;
    }

    /**
     * 计算余额
     * @param $recordDate
     * @param $subjectId
     * @param $vourcherNo
     * @param $khid
     * @param $supplierId
     * @param $staffId
     * @param $departmentId
     * @param $materialId
     * @param $cashId
     * @param $projectId
     * @return array
     */
    public function balance($recordDate, $subjectId, $vourcherNo, $khid, $supplierId, $staffId, $departmentId, $materialId, $cashId, $projectId): array
    {
        $assetField = array(
            "khid" => $khid,
            "supplierId" => $supplierId,
            "staffId" => $staffId,
            "departmentId" => $departmentId,
            "materialId" => $materialId,
            "cashId" => $cashId,
            "projectId" => $projectId,
        );
        $where = search(array("=" => $assetField));
        $voucherWhere = $assistWhere = '';
        if ($subjectId) {
            $assistWhere .= " and a.orderId = '$subjectId'";
            $voucherWhere .= " and subjectId = '$subjectId'";
        }
        //期初金额
        $jieInit = find(array('table' => "subject_assist as a join subject as b on a.orderId = b.id", 'single' => "b.direction = '借'" . $where . $assistWhere, 'field' => "ifnull(sum(a.initMoney),0) as money,ifnull(sum(a.initNum),0) as num"));
        $daiInit = find(array('table' => "subject_assist as a join subject as b on a.orderId = b.id", 'single' => "b.direction = '贷'" . $where . $assistWhere, 'field' => "ifnull(sum(a.initMoney),0) as money,ifnull(sum(a.initNum),0) as num"));

        if ($vourcherNo == '累计') {
            $jieVoucher = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' $voucherWhere and b.direction = '借' and a.recordDate <= '$recordDate'" . $where . voucherClass::joinWhere()));
            $daiVoucher = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' $voucherWhere and b.direction = '贷' and a.recordDate <= '$recordDate'" . $where . voucherClass::joinWhere()));
        } else {
            $jieVoucher = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' $voucherWhere and b.direction = '借' and if(a.recordDate='$recordDate',a.voucherNo<='$vourcherNo',a.recordDate <= '$recordDate')" . $where . voucherClass::joinWhere()));
            $daiVoucher = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' $voucherWhere and b.direction = '贷' and if(a.recordDate='$recordDate',a.voucherNo<='$vourcherNo',a.recordDate <= '$recordDate') " . $where . voucherClass::joinWhere()));
        }
        $jieVoucher['money'] = self::centToYuan($jieVoucher['money']) + $jieInit['money'];
        $daiVoucher['money'] = self::centToYuan($daiVoucher['money']) + $daiInit['money'];
        $jieVoucher['num'] += $jieInit['num'];
        $daiVoucher['num'] += $daiInit['num'];
        $balanceNum = abs($jieVoucher['num'] - $daiVoucher['num']);
        if ($jieVoucher['money'] == $daiVoucher['money']) {
            $direction = '平';
        } elseif ($jieVoucher['money'] > $daiVoucher['money']) {
            $direction = '借';
        } else {
            $direction = '贷';
        }
        $result = [
            'balanceNum' => voucherEditClass::formatZero($balanceNum),
            'balancePrice' => abs(accountDetailsClass::division($jieVoucher['money'] - $daiVoucher['money'], $balanceNum)),
            'direction' => $direction,
            'balance' => round(abs($jieVoucher['money'] - $daiVoucher['money']), 2)
        ];
        if (self::$isFormat) {
            $result = accountDetailsClass::formatArrayNumber($result);
        }
        return $result;
    }

    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $tr = [];
            $sql = static::rGet(self::$stid . self::page . 'sql');
            $startMonth = static::rGet(self::$stid . self::page . 'startMonth');
            $where = static::rGet(self::$stid . self::page . 'where');
            $assetField = json_decode(static::rGet(self::$stid . self::page . 'assetField'),true);
            $assitWhere = static::rGet(self::$stid . self::page . 'assitWhere');
            self::$isFormat = true;
            $title = array("日期", "凭证字", "科目", '摘要','客户编码','客户名称','供应商编码','供应商名称','员工编码','员工名称','部门编码','部门名称','存货编码','存货名称','现金流编码','现金流名称','项目编码','项目名称', '借方', '贷方', '方向', '余额');
            //获取查询结果
            $page['array'] = sqlFind($sql);
            foreach ($page['array'] as $array) {
                $all = find(array('table' => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "b.*,a.voucherNo,a.recordDate,a.voucherWordId", "where" => "b.subjectId = '$array[id]' " . $where .$assitWhere. voucherClass::joinWhere() . " order by a.recordDate asc,a.voucherNo asc,b.list"));
                if (is_array($all['array']) && count($all['array']) == 0) {
                    $result = $this->initMoney($assetField['khid'], $assetField['supplierId'], $assetField['staffId'], $assetField['departmentId'], $assetField['materialId'], $assetField['cashId'], $assetField['projectId'], $array, $startMonth);
                    $initDate = $startMonth . '-01';
                    $tr[] = [
                        $initDate,
                        '',
                        $array['code'] . $array['name'],
                        '期初余额',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        $result['jieMoney'],
                        $result['daiMoney'],
                        $result['direction'],
                        $result['balance'],
                    ];
                }
                foreach ($all['array'] as $index => $item) {
                    $voucherWord = query('voucher_word', "id = '$item[voucherWordId]'");
                    $kehu = query('kehu', "khid = '$item[khid]'");
                    $supplier = query('supplier', "id = '$item[supplierId]'");
                    $staff = query('staff', "stid = '$item[staffId]'");
                    $department = query('department', "id = '$item[departmentId]'");
                    $material = query('material', "id = '$item[materialId]'");
                    $cash = query('cash', "id = '$item[cashId]'");
                    $project = query('project', "id = '$item[projectId]'");
                    //期初
                    if ($index == 0 || (isset($all['array'][$index - 1]['subjectId']) && $item['subjectId'] != $all['array'][$index - 1]['subjectId'])) {
                        $result = $this->initMoney($assetField['khid'], $assetField['supplierId'], $assetField['staffId'], $assetField['departmentId'], $assetField['materialId'], $assetField['cashId'], $assetField['projectId'], $array, date('Y-m', strtotime($item['recordDate'])));
                        $initDate = date('Y-m', strtotime($item['recordDate'])) . '-01';
                        $tr[] = [
                            $initDate,
                            '',
                            $array['code'] . $array['name'],
                            '期初余额',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            $result['jieMoney'],
                            $result['daiMoney'],
                            $result['direction'],
                            $result['balance'],
                        ];
                    }
                    //中间的内容
                    $item['money'] = voucherClass::zeroToEmpty(number_format(self::centToYuan($item['money']), 2));
                    $pinzheng = $voucherWord['word'] . '-' . $item['voucherNo'];
                    if ($item['direction'] == '借') {
                        $jie = $item['money'];
                        $dai = '';
                    } else {
                        $jie = '';
                        $dai = $item['money'];
                    }
                    $result = $this->balance($item['recordDate'], $item['subjectId'], $item['voucherNo'], $assetField['khid'], $assetField['supplierId'], $assetField['staffId'], $assetField['departmentId'], $assetField['materialId'], $assetField['cashId'], $assetField['projectId']);
                    $tr[] = [
                        $item['recordDate'],
                        $pinzheng,
                        $array['code'] . $array['name'],
                        $item['summary'],
                        $kehu['orderNo'],
                        $kehu['companyName'],
                        $supplier['code'],
                        $supplier['name'],
                        $staff['orderNo'],
                        $staff['name'],
                        $department['orderNo'],
                        $department['name'],
                        $material['code'],
                        $material['name'],
                        $cash['code'],
                        $cash['name'],
                        $project['orderNo'],
                        $project['name'],
                        $jie,
                        $dai,
                        $result['direction'],
                        $result['balance'],
                    ];
                    //本期累计和本年累计
                    if ((isset($all['array'][$index + 1]['subjectId']) && ($item['subjectId'] != $all['array'][$index + 1]['subjectId'] || date('Y-m', strtotime($all['array'][$index + 1]['recordDate'])) != date('Y-m', strtotime($item['recordDate'])))) ||
                        !isset($all['array'][$index + 1]['subjectId'])
                    ) {
                        $day = sprintf("%02d", date('t', strtotime($item['recordDate'])));
                        $endMonthDate = date('Y-m-' . $day, strtotime($item['recordDate']));
                        $result = $this->monthBalance($assetField['khid'], $assetField['supplierId'], $assetField['staffId'], $assetField['departmentId'], $assetField['materialId'], $assetField['cashId'], $assetField['projectId'], date('Y-m', strtotime($item['recordDate'])), $item['subjectId']);
                        $balance =$this->balance($item['recordDate'], $item['subjectId'], '累计', $assetField['khid'], $assetField['supplierId'], $assetField['staffId'], $assetField['departmentId'], $assetField['materialId'], $assetField['cashId'], $assetField['projectId']);
                        $totalBalance = $this->monthBalance($assetField['khid'], $assetField['supplierId'], $assetField['staffId'], $assetField['departmentId'], $assetField['materialId'], $assetField['cashId'], $assetField['projectId'], date('Y-m', strtotime($item['recordDate'])), $array['id'], 'year');
                        $tr[] = [
                            $endMonthDate,
                            '',
                            $array['code'] . $array['name'],
                            '本期合计',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            $result['jieMoney'],
                            $result['daiMoney'],
                            $balance['direction'],
                            $balance['balance'],
                        ];
                        $tr[] = [
                            $endMonthDate,
                            '',
                            $array['code'] . $array['name'],
                            '本年累计',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            $totalBalance['jieMoney'],
                            $totalBalance['daiMoney'],
                            $balance['direction'],
                            $balance['balance'],
                        ];
                    }
                }
            }
            $text = $this->control['name'] . "导出了" . self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $tr, self::title . ".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }
}

